package com.ruoyi.contest.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.contest.domain.Award;
import com.ruoyi.contest.domain.AwardPerson;
import com.ruoyi.contest.domain.SubContest;
import com.ruoyi.contest.domain.Teacher;
import com.ruoyi.contest.domain.vo.ImportAwardVo;
import com.ruoyi.contest.domain.vo.SaveAwardVo;
import com.ruoyi.contest.mapper.AwardMapper;
import com.ruoyi.contest.mapper.AwardPersonMapper;
import com.ruoyi.contest.mapper.SubContestMapper;
import com.ruoyi.contest.mapper.TeacherMapper;
import com.ruoyi.contest.service.IAwardPersonService;
import com.ruoyi.contest.service.IAwardService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 获奖登记Service业务层处理
 *
 * @author lsyonlygoddes
 * @date 2023-02-14
 */
@Service
@RequiredArgsConstructor
public class AwardServiceImpl extends ServiceImpl<AwardMapper, Award> implements IAwardService {

    private final AwardPersonMapper awardPersonMapper;
    private final IAwardPersonService awardPersonService;
    private final SubContestMapper subContestMapper;
    private final TeacherMapper teacherMapper;

    private final RestTemplate restTemplate;

    private final String BASE_URL = "http://120.46.206.228:8080/stuManage/stu/";

    /**
     * 查询获奖登记列表
     *
     * @param award 获奖登记
     * @return 获奖登记
     */
    @Override
    public List<Award> selectAwardList(Award award) {
        List<Award> list = baseMapper.selectAwardList(award);
        if (list != null) {
            for (Award a : list) {
                Map<String, Object> params = new HashMap<>();
                String subContestName = "";
                SubContest subContest = subContestMapper.selectById(a.getSubContestId());
                String guideTeacherNames = getGuideTeacherNames(a.getAwardId());
                String contestStuNames = getContestStuNames(a.getAwardId());
                if (subContest != null) {
                    subContestName = subContest.getName();
                }
                params.put("subContestName", subContestName);
                params.put("guideTeachers", guideTeacherNames);
                params.put("contestStuNames", contestStuNames);
                a.setParams(params);
            }
        }

        return list;
    }

    private String getGuideTeacherNames(Long awardId) {
        StringBuilder guideTeacherNames = new StringBuilder();
        List<AwardPerson> teacherList = awardPersonMapper.selectList(new QueryWrapper<AwardPerson>().eq("award_id", awardId).eq("person_type", 0));
        if (teacherList != null) {
            for (AwardPerson teacher : teacherList) {
                guideTeacherNames.append(teacher.getPersonName()).append(",");
            }
        }
        String res = guideTeacherNames.toString();
        if (res.length() == 0) {
            return "";
        }
        return res.substring(0, res.length() - 1);
    }

    private String getContestStuNames(Long awardId) {
        StringBuilder contestStuNames = new StringBuilder();
        List<AwardPerson> stuList = awardPersonMapper.selectList(new QueryWrapper<AwardPerson>().eq("award_id", awardId).eq("person_type", 1));
        if (stuList != null) {
            for (AwardPerson stu : stuList) {
                contestStuNames.append(stu.getPersonName()).append(",");
            }
        }
        String res = contestStuNames.toString();
        if (res.length() == 0) {
            return "";
        }
        return res.substring(0, res.length() - 1);
    }

    private List<AwardPerson> guideTeacherList(Long awardId) {
        List<AwardPerson> guideTeachers = awardPersonMapper.selectList(new QueryWrapper<AwardPerson>().eq("award_id", awardId).eq("person_type", 0));
        if (guideTeachers != null) {
            return guideTeachers;
        } else {
            return Collections.emptyList();
        }
    }

    private List<AwardPerson> contestStuList(Long awardId) {
        List<AwardPerson> contestStuList = awardPersonMapper.selectList(new QueryWrapper<AwardPerson>().eq("award_id", awardId).eq("person_type", 1));
        if (contestStuList != null) {
            return contestStuList;
        } else {
            return Collections.emptyList();
        }
    }

    @Transactional
    @Override
    public int saveAward(SaveAwardVo vo) {
        Award award = new Award();
        BeanUtils.copyProperties(vo, award);
        award.setAttachmentUrl(vo.getAttachmentUrl());
        award.setCreateBy(SecurityUtils.getUsername());
        award.setCreateTime(new Date());
//        award.setUpdateBy(SecurityUtils.getUsername());
//        award.setUpdateTime(new Date());
        baseMapper.insert(award);
        List<AwardPerson> guideTeacherList = vo.getGuideTeacherList();
        if (guideTeacherList != null) {
            for (AwardPerson awardPerson : guideTeacherList) {
                awardPerson.setAwardId(award.getAwardId());
                awardPerson.setPersonType("0");
                awardPerson.setCreateBy(SecurityUtils.getUsername());
                awardPerson.setCreateTime(new Date());
//                awardPerson.setUpdateBy(SecurityUtils.getUsername());
//                awardPerson.setUpdateTime(new Date());
                awardPersonMapper.insert(awardPerson);
            }
        }
        List<AwardPerson> contestStuList = vo.getContestStuList();
        if (contestStuList != null) {
            for (AwardPerson awardPerson : contestStuList) {
                awardPerson.setAwardId(award.getAwardId());
                awardPerson.setPersonType("1");
                awardPerson.setCreateBy(SecurityUtils.getUsername());
                awardPerson.setCreateTime(new Date());
//                awardPerson.setUpdateBy(SecurityUtils.getUsername());
//                awardPerson.setUpdateTime(new Date());
                awardPersonMapper.insert(awardPerson);
            }
        }
        return 1;
    }

    @Override
    public SaveAwardVo awardDetail(Long awardId) {
        SaveAwardVo saveAwardVo = new SaveAwardVo();
        Award award = getById(awardId);
        BeanUtils.copyProperties(award, saveAwardVo);
        SubContest subContest = subContestMapper.selectById(saveAwardVo.getSubContestId());
        String name = "";
        if (subContest != null) {
            name = subContest.getName();
        }
        saveAwardVo.setSubContestName(name);
        saveAwardVo.setGuideTeacherList(guideTeacherList(awardId));
        saveAwardVo.setContestStuList(contestStuList(awardId));
        return saveAwardVo;
    }

    @Transactional
    @Override
    public int updateAward(SaveAwardVo vo) {
        Award award = new Award();
        BeanUtils.copyProperties(vo, award);
        updateById(award);
        List<AwardPerson> guideTeacherList = vo.getGuideTeacherList();
        if (guideTeacherList != null) {
            awardPersonService.updateBatchById(guideTeacherList);
            /*for (AwardPerson teacher : guideTeacherList) {
                awardPersonMapper.update(teacher,new UpdateWrapper<AwardPerson>().eq("award_id",vo.getAwardId()).eq("person_type",0));
            }*/
        }
        awardPersonMapper.delByAwardIdAndPersonType(vo.getAwardId(), 1L);
        List<AwardPerson> contestStuList = vo.getContestStuList();
        if (contestStuList != null) {
            contestStuList.forEach(item -> {
                item.setPersonType("1");
                item.setAwardId(vo.getAwardId());
            });
            awardPersonService.saveBatch(contestStuList);
//            for (AwardPerson stu : contestStuList) {
//                awardPersonMapper.update(stu,new UpdateWrapper<AwardPerson>().eq("award_id",vo.getAwardId()).eq("person_type",1));
//            }
        }
        return 1;
    }

    @Transactional
    @Override
    public String importAwardInfo(List<ImportAwardVo> awardList, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        if (StringUtils.isNull(awardList) || awardList.size() == 0) {
            throw new ServiceException("获奖信息不能为空！");
        }
        for (ImportAwardVo vo : awardList) {
            try {
                Award award = new Award();
                BeanUtils.copyProperties(vo, award);
                SubContest subContest = subContestMapper.selectOne(new QueryWrapper<SubContest>().eq("name", vo.getSubContestName()));
                if (subContest == null) {
                    failureMsg.append("竞赛名称").append("<span style=\"color: orange\">不正确</span>").append("!  ");
                    failureNum++;
                    continue;
                }
                award.setSubContestId(subContest.getSubContestId());
                award.setContestId(subContest.getContestId());
                award.setCreateBy(SecurityUtils.getUsername());
                award.setCreateTime(new Date());
                save(award);
                Long awardId = award.getAwardId();
                // 教师
                String guideTeacherList = vo.getGuideTeacherList();
                if (guideTeacherList != null) {
                    String[] teacherArr = guideTeacherList.split(",");
                    for (String teacherInfo : teacherArr) {
                        String[] idNameOrderNumCondeArr = teacherInfo.split("-");
                        AwardPerson awardPerson = new AwardPerson();
                        awardPerson.setAwardId(awardId);
                        awardPerson.setPersonType("0");
                        Long teacherId = Long.valueOf(idNameOrderNumCondeArr[0]);
                        Teacher teacher = teacherMapper.selectById(teacherId);
                        if (teacher == null) {
                            failureMsg.append("教师工号").append("<span style=\"color: orange\">不正确</span>").append("!请按要求填写指导老师信息！");
                            failureNum++;
                            continue;
                        }
                        awardPerson.setPersonId(teacher.getTeacherId());
                        awardPerson.setPersonName(teacher.getName());
                        awardPerson.setOrderNum(Long.valueOf(idNameOrderNumCondeArr[2]));
                        awardPerson.setConDegree(Long.valueOf(idNameOrderNumCondeArr[3]));
                        awardPerson.setCreateBy(SecurityUtils.getUsername());
                        awardPerson.setCreateTime(new Date());
                        awardPersonMapper.insert(awardPerson);
                    }
                }
                // 学生
                String contestStuList = vo.getContestStuList();
                if (contestStuList != null) {
                    String[] stuArr = contestStuList.split(",");
                    for (String stuInfo : stuArr) {
                        String[] idNameOrderNumCondeArr = stuInfo.split("-");
                        AwardPerson awardPerson = new AwardPerson();
                        awardPerson.setAwardId(awardId);
                        awardPerson.setPersonType("1");
                        Long stuId = Long.valueOf(idNameOrderNumCondeArr[0]);
                        JSONObject jsonObject = restTemplate.getForObject(BASE_URL + stuId, JSONObject.class);
                        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) jsonObject.get("data");
                        if (map == null) {
                            failureMsg.append("学生编号").append("<span style=\"color: orange\">不正确</span>").append("!请按要求填写参赛学生信息！");
                            failureNum++;
                            continue;
                        }
                        String name = (String) map.get("name");
                        awardPerson.setPersonId(stuId);
                        awardPerson.setPersonName(name);
                        awardPerson.setOrderNum(Long.valueOf(idNameOrderNumCondeArr[2]));
                        awardPerson.setConDegree(Long.valueOf(idNameOrderNumCondeArr[3]));
                        awardPerson.setCreateBy(SecurityUtils.getUsername());
                        awardPerson.setCreateTime(new Date());
                        awardPersonMapper.insert(awardPerson);
                    }
                }
                successMsg.append(vo.getSubContestName()).append("  导入").append("<span style=\"color: green\">成功</span>").append("<br/>");
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、竞赛名称 " + vo.getSubContestName() + " 导入<span style=\"color: red\">失败</span>：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入<span style=\"color: red\">失败</span>！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入<span style=\"color: green\">成功</span>！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
